package com.imeem.api.services;

import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.util.Hashtable;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import com.imeem.api.results.IResultCallback;
import com.imeem.api.results.ResultData;
import com.imeem.api.results.ResultStatus;
import com.imeem.api.types.MediaTypes;
import com.imeem.api.xml.MusicDataResultHandler;

public class MediaService extends CoreService
{
   public MediaService(String apiKey, String apiSecret) throws NoSuchAlgorithmException
   {
      super(apiKey, apiSecret);
   }
   
   public void search(String query, String mediaType, int offset, int numResults, IResultCallback function, Object context)
   {
      Hashtable<String, String> params = super.getBaseParameters();
      params.put("query", query);
      params.put("mediaType", mediaType);
      params.put("offset", Integer.toString(offset));
      params.put("numResults", Integer.toString(numResults));
      
      try
      {
         InputStream instream = super.invoke("mediaSearch", params);
         XMLReader parser = XMLReaderFactory.createXMLReader();
         if (0 == MediaTypes.MUSIC.compareTo(mediaType))
            parser.setContentHandler(new MusicDataResultHandler(function, context));
         else if (0 == MediaTypes.PHOTO.compareTo(mediaType))
            parser.setContentHandler(null);
         else if (0 == MediaTypes.VIDEO.compareTo(mediaType))
            parser.setContentHandler(null);
         
         parser.parse(new InputSource(instream));
      }
      catch (SAXException e)
      {
         ResultStatus fail = new ResultStatus(-1, "error creating or parsing XML", e.getMessage());
         ResultData result = new ResultData(fail, null, context);
         function.callback(result);
      }
      catch (IOException e)
      {
         ResultStatus fail = new ResultStatus(-1, "error reading from stream", e.getMessage());
         ResultData result = new ResultData(fail, null, context);
         function.callback(result);
      }
   }
}
